"use client";

import { Form, TextArea } from "@/components/Form";
import React, { useState } from "react";
import yaml from "js-yaml";
import ClientLoading from "@/components/ClientLoading";
import { POST } from "@/utils/fetch";
import { useRouter } from "next/navigation";

export default function NodeImportUI() {
  const [data, setData] = useState({ data: "", clear: false });
  const [isLoading, setLoading] = useState(false);
  const router = useRouter();

  const submitHandler = async () => {
    setLoading(true);
    try {
      const nodes: Subscribe[] | unknown = yaml.load(data.data);
      //   console.log(nodes);

      if (!nodes) {
        throw new Error("数据解析失败！");
      }

      const postData: SubscribeImport = {
        nodes: nodes as Subscribe[],
        clear: data.clear,
      };
      const resp: JsonResp<{ num: number }> = await POST("/node/import", {
        ...postData,
      });
      if (resp.code !== 0) {
        throw new Error(resp.msg);
      }
      //   console.log(resp.data);
      router.push(
        `/node?msg=成功导入${resp.data.num}个节点&_r=${Math.random()}`
      );
    } catch (e) {
      alert((e as Error).message);
      console.log(e);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {isLoading && <ClientLoading />}
      {/* <div>{JSON.stringify(data)}</div> */}
      <Form onSubmit={submitHandler}>
        <TextArea
          label="节点数据（yaml）"
          rows={10}
          value={data.data}
          onChange={(e) => {
            setData({ ...data, data: e.target.value.trim() });
          }}
          required
        />
        <div className="block">
          <div className="mt-2">
            <div>
              <label className="inline-flex items-center">
                <input
                  type="checkbox"
                  checked={data.clear}
                  onChange={(e) => {
                    setData({ ...data, clear: e.target.checked });
                  }}
                />
                <span className="ml-2">清空现有节点</span>
              </label>
            </div>
          </div>
        </div>
      </Form>
    </>
  );
}
